<script setup lang="ts">
import { Refresh, Search } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import {
  FriendService,
  UserApplyDto,
  UserQueryCriteria,
  UserVo,
} from '/@/api/openapi'
import { ElMessage } from 'element-plus'
import { useUserFriendStore, useUserStore } from '/@/store'
import { storeToRefs } from 'pinia'

const tableRef = ref()
const searchParams = ref<UserQueryCriteria>({
  pageNum: 1,
  pageSize: 10,
})
const total = ref(0)
const store = useUserStore()
const userFriendStore = useUserFriendStore()
const { allUser } = storeToRefs(userFriendStore)
const loading = ref(false)
const searchKeyword = ref('')

const userApplyDto = ref<UserApplyDto>({
  applyInfo: '',
  toUid: 0,
})
const centerDialogVisible = ref<boolean>(false)

const handleCurrentChange = (val: number) => {
  searchParams.value.pageNum = val
  loadData()
}

const loadData = async () => {
  loading.value = true
  try {
    await userFriendStore.updateAllUser(searchParams.value)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  searchParams.value.pageNum = 1
  loadData()
}

onMounted(() => {
  if (store.isSign) {
    loadData()
  }
})

const handleApply = async () => {
  if (!userApplyDto.value.applyInfo.trim()) {
    ElMessage({
      type: 'warning',
      message: '请填写申请理由',
    })
    return
  }

  try {
    const res = await FriendService.addUserApply(userApplyDto.value)
    ElMessage({
      type: 'success',
      message: res.data,
    })
    centerDialogVisible.value = false
    userApplyDto.value.applyInfo = ''
  } catch (error) {
    ElMessage({
      type: 'error',
      message: error as string,
    })
  }
}

const openApplyDialog = (data: UserVo) => {
  if (data.id === undefined) {
    ElMessage({
      type: 'error',
      message: '用户ID不能为空',
    })
    return
  }
  userApplyDto.value.toUid = data.id
  userApplyDto.value.applyInfo = ''
  centerDialogVisible.value = true
}
</script>

<template>
  <div class="user-list-container">
    <div class="header">
      <h2 class="title">所有用户</h2>
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户"
          class="search-input"
          :prefix-icon="Search"
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>

    <div class="table-container">
      <el-button
        @click="loadData"
        class="refresh-btn"
        :loading="loading"
        type="primary"
        plain
      >
        <el-icon><Refresh /></el-icon>
        刷新列表
      </el-button>

      <div class="table-wrapper">
        <el-table
          :ref="tableRef"
          :data="allUser.records"
          style="width: 100%"
          v-loading="loading"
          :empty-text="'暂无用户'"
          border
          stripe
        >
          <el-table-column prop="username" label="用户名称" min-width="120">
            <template #default="{ row }">
              <div class="user-info">
                <el-avatar :size="32" :src="row.avatar || ''" />
                <span class="username">{{ row.username }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="signature"
            label="签名"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column
            prop="email"
            label="邮箱"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column
            prop="phone"
            label="电话"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                size="small"
                @click="openApplyDialog(row)"
              >
                <i class="fa fa-add"></i>
                申请好友
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="allUser.total"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.pageNum"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      v-model="centerDialogVisible"
      title="申请好友"
      width="30%"
      align-center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="dialog-content">
        <el-input
          v-model="userApplyDto.applyInfo"
          type="textarea"
          :rows="4"
          placeholder="请输入申请理由"
          maxlength="200"
          show-word-limit
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleApply"> 确认申请 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-list-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.table-container {
  margin-top: 20px;
  height: calc(100vh - 200px);
  display: flex;
  flex-direction: column;
}

.table-wrapper {
  flex: 1;
  overflow: auto;
  margin-bottom: 20px;
}

.refresh-btn {
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-weight: 500;
  color: #303133;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

.pagination-container {
  margin-top: auto;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.dialog-content {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media screen and (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 16px;
  }

  .search-box {
    width: 100%;
  }

  .search-input {
    width: 100%;
  }
}
</style>
